package com.peng.leetcode.array;

import java.util.*;

/**
 * Intersection
 * 349. 两个数组的交集
 * https://leetcode.cn/problems/intersection-of-two-arrays/
 *
 * @author: lupeng6
 * @create: 2023/3/30 16:15
 */
public class Intersection {

    public int[] intersection(int[] nums1, int[] nums2) {
        Set<Integer> s1 = new HashSet<>();
        Arrays.stream(nums1).forEach(s1::add);
        Set<Integer> s2 = new HashSet<>();
        Arrays.stream(nums2).forEach(s2::add);
        s1.retainAll(s2);
        int[] ans = new int[s1.size()];
        int idx = 0;
        for (Integer i : s1) {
            ans[idx++] = i;
        }
        return ans;
    }

    public int[] intersection1(int[] nums1, int[] nums2) {
        Arrays.sort(nums1);
        Arrays.sort(nums2);
        List<Integer> ans = new ArrayList<>();
        int i1 = 0, i2 = 0;
        while (i1 < nums1.length && i2 < nums2.length) {
            if (nums1[i1] == nums2[i2]) {
                if (ans.size() == 0 || ans.get(ans.size() - 1) == nums1[i1]) {
                    ans.add(nums1[i1]);
                }
                i1++;
                i2++;
            } else if (nums1[i1] < nums2[i2]) {
                i1++;
            } else {
                i2++;
            }
        }
        return ans.stream().mapToInt(i -> i).toArray();
    }
}
